/* eslint-disable */

export default {
  data () {
    return {
      queryTxt: "",
      state: true,
      total: 1,
      pagenum: '',
      usersData: [
        {
          id: 1,
          mobile: "123123",
          username: "王小虎",
          email: "上海市普陀区金沙江路 1518 弄"
        }
      ],
      dialogFormVisible: false,
      editShow: false,
      addUserForm: {
        id: '',
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
      }
    };
  },
  methods: {
    /* 读取用户列表 */
    async loadUsersList (e, query) {
      let config = {
        params: { query, pagenum: e || 1, pagesize: 2 }
      }
      let res = await this.$axios.get('users', config)
      this.usersData = res.data.data.users;
      this.total = res.data.data.total;
      this.pagenum = e

    },
    /* 添加新用户 */
    showAddUserBox () {
      this.addUserForm = {
        id: '',
        username: '',
        password: '',
        email: '',
        mobile: ''
      }
      this.dialogFormVisible = true
    },
    addUser () {
      this.$refs.addUserForm.validate(async valid => {
        if (!valid) { return this.$message.error('表格有误') }

        else {
          let res = await this.$axios.post('users', this.addUserForm)
          if (res.data.meta.status === 201) { this.$message.success('创建成功') }
          else if (res.data.meta.status === 400) { return this.$message.error('创建失败, ' + res.data.meta.msg) }

          this.dialogFormVisible = false
          this.loadUsersList(this.pagenum)
        }
      })

    },
    /* 删除用户 */
    async del (id) {
      let res = await this.$axios.delete(`users/${id}`)
      if (res.data.meta.status === 200) {
        this.loadUsersList(1)
        return this.$message.success(res.data.meta.msg)
      }
      this.$message.error('删除失败, 服务器未响应')
    },
    /* 编辑用户 */
    edit (row) {
      let { id, username, email, mobile } = row
      this.addUserForm = { id, username, email, mobile }
      this.editShow = true
    },
    /* 修改用户 */
    async putUser (id) {
      let res = await this.$axios.put(`users/${id}`, this.addUserForm)
      this.$message.success(res.data.meta.msg)
      this.editShow = false
      this.loadUsersList(this.pagenum)
    },
    userBoxClosed () {
      this.$refs.addUserForm.resetFields()
    }
  },
  created () {
    this.loadUsersList();
  }
};
